package org.idea.web.socket.mq;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.idea.web.socket.config.MqProducerConfig;
import org.idea.web.socket.dto.BroadcastMqDTO;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;

/**
 * 消息广播发送端
 *
 * @Author linhao
 * @Date created in 10:43 下午 2021/5/9
 */
@Component
@Slf4j
public class BroadcastMqProducer {

    @Resource
    private DefaultMQProducer defaultMQProducer;

    @Resource
    private MqProducerConfig mqProducerConfig;

    private static String TOPIC = "ws-topic";
    private static String TAGS = "ws-tag";


    public static Integer ALL_USER_RECEIVE_TYPE = 1;
    public static Integer ONE_USER_RECEIVE_TYPE = 2;

    public SendResult sendWebSocketToUser(String destSessionKey,String msg) {
        if (StringUtils.isEmpty(msg)) {
            log.error("[sendWebSocketToUser] msg can not be null!");
            return null;
        }
        Message message = null;
        SendResult sendResult = null;
        try {
            BroadcastMqDTO broadcastMqDTO = new BroadcastMqDTO();
            broadcastMqDTO.setEventType(ONE_USER_RECEIVE_TYPE);
            broadcastMqDTO.setMessage(msg);
            broadcastMqDTO.setSessionKey(destSessionKey);
            message = new Message(TOPIC, TAGS, (JSON.toJSONString(broadcastMqDTO)).getBytes(RemotingHelper.DEFAULT_CHARSET));
            sendResult = defaultMQProducer.send(message);
        } catch (Exception e) {
            log.error("[sendWebSocketBroadcastMsg] e is ", e);
        }
        return sendResult;
    }

    public SendResult sendWebSocketBroadcastMsg(String msg) {
        if (StringUtils.isEmpty(msg)) {
            log.error("[sendWebSocketBroadcastMsg] msg can not be null!");
            return null;
        }
        Message message = null;
        SendResult sendResult = null;
        try {
            BroadcastMqDTO broadcastMqDTO = new BroadcastMqDTO();
            broadcastMqDTO.setEventType(ALL_USER_RECEIVE_TYPE);
            broadcastMqDTO.setMessage(msg);
            message = new Message(TOPIC, TAGS, (JSON.toJSONString(broadcastMqDTO)).getBytes(RemotingHelper.DEFAULT_CHARSET));
            sendResult = defaultMQProducer.send(message);
        } catch (Exception e) {
            log.error("[sendWebSocketBroadcastMsg] e is ", e);
        }
        return sendResult;
    }

}
